import React, { useCallback } from 'react';
import classnames from 'classnames';
import './index.less';

export interface InnerTabBarProps {}

interface TabBarItemProps {
  /**
   * 标题
   */
  title: string;
  /**
   * 默认icon， JSX.Element
   */
  icon: JSX.Element;
  /**
   * 高亮icon， JSX.Element
   */
  selectedIcon: JSX.Element;
  /**
   * 是否选中
   */
  selected: boolean;
  /**
   * 点击事件
   */
  onPress?: () => void;
}

const TabItem: React.FunctionComponent<TabBarItemProps> = (props) => {
  return (
    <div className={classnames('hr-tabs-pane')} style={{ height: props.children ? '100%' : 0 }}>
      {props.children}
    </div>
  );
};

const InnerTabBar: React.SFC<InnerTabBarProps> = (props) => {
  const getTabs = () => {
    const tabs = [] as TabBarItemProps[];
    React.Children.forEach(props.children, (c: any) => {
      if (c) {
        tabs.push({
          ...(c.props as TabBarItemProps),
        });
      }
    });
    return tabs;
  };
  const tabs = getTabs();

  const onPress = useCallback((callback) => {
    if (typeof callback === 'function') {
      callback();
    }
  }, []);

  return (
    <div className="hr-tab-bar">
      <div className="hr-tabs">
        <div className="hr-tabs-content-wrapper">{props.children}</div>
        <div className="hr-tabs-wrapper">
          <div className="hr-tabs-bar">
            {tabs.map((item) => (
              <div key={item.title} className="hr-tabs-item" onClick={() => onPress(item.onPress)}>
                {item.icon && (
                  <div className="hr-tabs-icon">
                    {item.selected ? item.selectedIcon : item.icon}
                  </div>
                )}
                {item.title}
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

type InnerTabBar = typeof InnerTabBar;

interface TabBar extends InnerTabBar {
  Item: typeof TabItem;
}

const TabBar = InnerTabBar as TabBar;
TabBar.Item = TabItem;

export default TabBar;
